<template>
  <div>
    <el-input 
      v-model="value" 
      :placeholder="setting.writerPlaceholder || '请输入'" 
      clearable 
      show-word-limit
      :maxlength="maxLength"
      :minlength="minLength"
      :readonly="props.disabled"
    />
  </div>
</template>

<script setup>
import { computed, onMounted } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  setting: {
    type: Object,
    default: () => {}
  },
  formRules: {
    type: Object,
    default: () => {}
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:modelValue', 'update:formRules'])

const value = computed({
  get: () => props.modelValue,
  set: (val) => {
    emits('update:modelValue', val)
  }
})

const formRules = computed({
  get: () => props.formRules,
  set: (val) => {
    emits('update:formRules', val)
  }
})

// 计算最大长度
const maxLength = computed(() => {
  const { wordsNumFormat, wordsNum, wordsNumRange } = props.setting
  switch (wordsNumFormat) {
    case 0: // 不限制
      return undefined
    case 1: // 不超过
      return wordsNum
    case 2: // 不少于
      return undefined
    case 3: // 固定为
      return wordsNum
    case 4: // 介于
      return wordsNumRange[1]
    default:
      return undefined
  }
})

// 计算最小长度
const minLength = computed(() => {
  const { wordsNumFormat, wordsNum, wordsNumRange } = props.setting
  switch (wordsNumFormat) {
    case 0: // 不限制
      return undefined
    case 1: // 不超过
      return undefined
    case 2: // 不少于
      return wordsNum
    case 3: // 固定为
      return wordsNum
    case 4: // 介于
      return wordsNumRange[0]
    default:
      return undefined
  }
})

// 生成校验规则
const generateRules = () => {
  const rules = []
  const { wordsNumFormat, wordsNum, wordsNumRange } = props.setting

  if (props.setting.require) {
    rules.push({ required: true, message: '此题为必填题', trigger: 'blur' })
  }

  switch (wordsNumFormat) {
    case 1: // 不超过
      rules.push({ 
        max: wordsNum, 
        message: `字数不能超过${wordsNum}个字`, 
        trigger: 'blur' 
      })
      break
    case 2: // 不少于
      rules.push({ 
        min: wordsNum, 
        message: `字数不能少于${wordsNum}个字`, 
        trigger: 'blur' 
      })
      break
    case 3: // 固定为
      rules.push({ 
        min: wordsNum, 
        max: wordsNum, 
        message: `字数必须为${wordsNum}个字`, 
        trigger: 'blur' 
      })
      break
    case 4: // 介于
      rules.push({ 
        min: wordsNumRange[0], 
        max: wordsNumRange[1], 
        message: `字数必须介于${wordsNumRange[0]}至${wordsNumRange[1]}个字之间`, 
        trigger: 'blur' 
      })
      break
  }

  // 手机号
  rules.push({ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' })

  formRules.value[props.setting.formItemId] = rules
}

onMounted(() => {
  generateRules()
})
</script>

<style lang="scss" scoped>
:deep(.el-input) {
  width: 100%;
}
</style>
